<template>
<!--  <div class="outerBox" ref="outerDom" @scroll="getScrollTop">-->
  <div class="outerBox" ref="outerDom">
    <div class="biliMainHeader">
      <!--detailNav组件 顶部导航栏-->
      <detailNav></detailNav>
    </div>
    <div class="video-container">
      <!--视频详情页 左部分-->
      <leftContainer></leftContainer>
      <!--视频详情页 右部分-->
      <rightContainer></rightContainer>
    </div>
    <Transition name="mask">
      <div class="toast-mask" v-show="isShowError">{{ errorMsg }}</div>
    </Transition>
    <!-- 回顶部按钮为一张50*50的图片 -->
    <!-- btnFlag 控制图片显示隐藏 -->
    <!-- backTop 回顶部的方法 -->
    <!--    <div class="scrollBox" v-show="isShow" @click="goBack">
          <img src="../assets/img/backtop.png" alt=""/>
        </div>-->
  </div>
</template>

<script>
import detailNav from '../components/detailComponent/detailNav.vue'
import leftContainer from './detailComponent/leftContainer.vue'
import rightContainer from './detailComponent/rightContainer.vue'
import {computed} from 'vue'
import io from '../../node_modules/socket.io/client-dist/socket.io.js'

export default {
  /**视频详情页组件*/
  name: 'detailView',
  components: {
    detailNav,
    leftContainer,
    rightContainer
  },
  data() {
    return {
      isShowError: false,
      errorMsg: '',
      detailList: [],
      numClients: 0,
      isInit: false,
      scrollTop: 0, //默认距离顶部的距离
      isShow: false, //控制返回顶部按钮的显隐
      scrollTrigger: false, //默认初始值
      timer: null, //获取在线观看人数定时器
      curVideoId:null,//当前播放视频id
      isSpeak:true
    }
  },
  methods: {
    //获取在线观看人数定时任务
    getViewsNumberTask() {
      if (this.timer == null) {
        this.timer = setInterval(() => {
          // 接收房间人数信息
          this.socket.emit("getViewsNumber", {
            videoId: this.detailList.id,
            userId: this.$store.state.userInfo.userId
          })
        }, 10000)
      }
    },
    // 返回顶部事件
    goBack() {
      let that = this; // 防止this指向问题
      // 防止频繁点击，故返回顶部后设置scrollTrigger为初始值
      if (that.scrollTrigger) {
        return;
      }
      // 获取当前距离顶部的距离
      let scrollTop = this.scrollTop;
      let steep = scrollTop / 2000;
      let timer = setInterval(() => {
        that.scrollTrigger = true;
        // 滚动的速度逐渐变快，第一次走2000/1，然后减去已走的距离，下一次用剩下的距离再减去步进值，步进值也是不断变化，这样速度会越来越快
        scrollTop -= steep;
        // 步进值不改变的话会匀速缓慢上滑，不断增加步进值上滑的距离增加，视觉效果速度变快
        steep += 20;
        if (scrollTop <= 0) {
          clearInterval(timer);
          that.scrollTrigger = false;
        }
        that.$refs.outerDom.scrollTop = scrollTop;
      }, 30);
    },
    // 监听滚动条
    getScrollTop(e) {
      let that = this; // 防止this指向问题
      // 设备一屏的高度
      let clientHeight =
          document.documentElement.clientHeight || document.body.clientHeight;
      let scrollTop = e.srcElement.scrollTop;
      this.scrollTop = scrollTop;
      // 判断距离顶部多少显示回到顶部图标
      if (scrollTop > clientHeight) {
        that.isShow = true;
      } else {
        that.isShow = false;
      }
    },
    // 显示信息
    showErrorMsg(msg) {
      this.errorMsg = msg
      this.isShowError = true
      setTimeout(() => {
        this.isShowError = false
      }, 2000)
    },
    async getEmojiList() {
      let res = await this.$util.get('hilihili/emojilist/list')
      if (res.code != 200) {
        this.showErrorMsg("表情获取失败")
      }
      this.$store.commit('saveEmojiList', res.data)

    },


    /**视频详情页 组件加载完成时触发*/
    async getDetail(videoId) {
      this.curVideoId = videoId
      this.loadingDetailList = true
      let res = await this.$util.get('hilihili/video/getDetail/' + videoId)
      // 没有该视频，跳转到404
      if (res.code == 106) {
        this.$router.push("/viewError")
        return
      }
      if (res.code != 200) return
      this.$bus.emit("getVideoUrl",res.data.link)
      // console.log("查询getDetail：",res.data)
      this.detailList = res.data

      if (!this.isInit) {
        /**老是报错先注释一下*/
        this.initSocket()
        //先清除页面定时器
        clearInterval(this.timer)
        this.timer = null
        //在开启定时任务
        this.getViewsNumberTask()
      }
    },
    //切换视频方法，供子孙组件调用 解决 合集类型视频，剧集类型视频 切换视频 视频观看 人数不准确问题
    switchVideo(videoId){
      this.isInit = false
      this.socket.emit('leaveRoom', {
        videoId: this.curVideoId,
        userId: this.$store.state.userInfo.userId
      });
      clearInterval(this.timer)
      this.timer = null
      this.socket.disconnect()
      this.getDetail(videoId)
    },
    initSocket() {
      /**
       * 连接socket服务端
       * this.socket = io('http://localhost:3001');
       * 监听name，接受发送的message
       * socket.on(socketName,message)
       * 发送message到socketName
       * socket.emit(socketName,message)
       * @type {boolean}
       */
      this.isInit = true
      //连接websocket后端服务器
      this.socket = io('http://localhost:3001?userId=' + this.$store.state.userInfo.userId);
      this.socket.on('connect', () => {
        console.log('Connected to server');
      });
      this.socket.on('disconnect', () => {
        console.log('disconnect to server');
      });
      // 加入房间
      this.socket.emit('joinRoom', {
        videoId: this.detailList.id,
        userId: this.$store.state.userInfo.userId
      });
      // 窗口关闭则退出房间 并清除页面定时器
      window.addEventListener('beforeunload', () => {
        this.socket.emit('leaveRoom', {
          videoId: this.detailList.id,
          userId: this.$store.state.userInfo.userId
        });
        clearInterval(this.timer)
        this.timer = null
      });
      // 接收房间人数信息
      this.socket.emit("getViewsNumber", {
        videoId: this.detailList.id,
        userId: this.$store.state.userInfo.userId
      })
      this.socket.on("getViewsNumber", (numClients) => {
        this.numClients = numClients
      });
    },
    getSpeak(isSpeak){
      console.log("getSpeak(isSpeak)" + isSpeak)
      this.isSpeak = isSpeak
    }
    // leaveHome() {
    //     this.socket.emit('leave room', this.detailList.id);
    // }
  },
  /** provide/inject 祖孙组件，甚至祖祖祖祖孙组件之间的通信。provide选项应该是一个对象或返回一个对象的函数。该对象包含可注入其子孙的property。
   */
  provide() {
    return {
      detailList: computed(() => this.detailList),
      numClients: computed(() => this.numClients),
      curVideoId: computed(() => this.curVideoId),
      switchVideo:computed(() => this.switchVideo),
      getSpeak:computed(() => this.getSpeak),
      isSpeak:computed(() => this.isSpeak)
    }
  },
  created() {
    // 查询表情数据
    this.getEmojiList()
    this.getDetail(this.$route.params.id)
    //先清除定时器

  },
  mounted() {

  },


  // beforeUnmount() {
  //     this.socket.emit('leave room', this.detailList.id);
  // }

}
</script>

<style scoped>
.toast-mask {
  position: fixed;
  top: 50%;
  left: 50%;
  display: flex;
  align-items: center;
  text-align: center;
  padding: 8px 12px;
  transform: translate(-50%, -50%);
  background: rgba(51, 51, 51, .8);
  border-radius: 4px;
  z-index: 3000;
  font-size: 14px;
  color: #fff;
}

/* 最外层盒子样式 */
.outerBox {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  /*关键设置overflow*/
  overflow-y: auto;
}

/* 返回顶部样式 */
.scrollBox {
  position: fixed;
  right: 60px;
  bottom: 30px;
  /*font-size: 22px;*/
  width: 50px;
  z-index: 99;
}

/*.scrollBox img{
  width: 50px;
}
!* 浏览器滚动条样式 *!
::-webkit-scrollbar {
  width: 4px;
  background: transparent;
}
::-webkit-scrollbar-thumb {
  background: rgb(174, 174, 174);
  border-radius: 50px;
}
::-webkit-scrollbar-track {
  background: transparent;
}*/

.biliMainHeader {
  height: 64px;
}

.video-container {
  max-width: 2540px;
  min-width: 1080px;
  margin: 0 auto;
  padding: 0 10px;
  display: flex;
  justify-content: center;
  position: relative;
  width: auto;
}
</style>
